import {
    Component, OnInit, Output, Input, EventEmitter, ViewChild, TemplateRef, HostBinding, NgZone, OnDestroy
} from '@angular/core';
import { NotifyService } from '@farris/ui-notify';
import { TreeNode } from '@farris/ui-treetable';
import { ElementPropertyConfig } from '@farris/ide-property-panel';
import { AppointmentCalendarField, AppointmentCalendarFieldService } from './calendar-field.service';
import { cloneDeep } from 'lodash-es';
import { FormSchemaEntityField$Type, DesignViewModelService } from '@farris/designer-services';
import { MessagerService } from '@farris/ui-messager';
import { MultiSelectComponent } from '@farris/ui-multi-select';


@Component({
    selector: 'app-calendar-fields-editor',
    templateUrl: './calendar-fields-editor.component.html',
    providers: [AppointmentCalendarFieldService]
})
export class CalendarFieldsEditorComponent implements OnInit, OnDestroy {
    @Output() closeModal = new EventEmitter<any>();
    @Output() submitModal = new EventEmitter<any>();
    @Input() value;
    @Input() editorParams = { viewModelId: '' };

    /** 是否显示属性面板 */
    @Input() showPropertyPanel = true;

    @ViewChild('footer') modalFooter: TemplateRef<any>;
    modalConfig = {
        title: '展示列编辑器',
        width: 1000,
        height: 700,
        showButtons: true,
        showMaxButton: true
    };
    // 筛选条字段
    fieldConfigs: Array<AppointmentCalendarField>;

    // 左侧树表数据
    treeData: TreeNode[] = [];

    // 当前可选的所有字段ID
    treeNodeIds: string[] = [];
    // plainTreeNodes: TreeNode[] = [];

    // 选中的字段
    selectedFieldIds = [];

    // 右侧选中行对应的schema字段信息
    selectedSchemaField;


    // 属性面板配置
    propertyConfig: ElementPropertyConfig[];

    // 属性面板值
    propertyData: AppointmentCalendarField;

    @HostBinding('class')
    class = 'd-flex  h-100';

    @ViewChild(MultiSelectComponent) multiSelectCmp: MultiSelectComponent;

    timer: any;

    constructor(
        private dgVMService: DesignViewModelService, private notifyService: NotifyService,
        private calendarFieldServ: AppointmentCalendarFieldService, private msgService: MessagerService,
        private ngZone: NgZone) { }

    ngOnInit(): void {
        if (!this.editorParams || !this.value) {
            this.fieldConfigs = [];
        } else {
            this.fieldConfigs = cloneDeep(this.value);
        }
        this.treeData = this.dgVMService.getAllFields2TreeByVMId(this.editorParams.viewModelId);

        this.filterAllowedType(this.treeData);
        this.selectedFieldIds = this.fieldConfigs.map(v => v.id);

        this.filterSchemFields();

        // 默认选中第一行
        if (this.selectedFieldIds.length && this.multiSelectCmp['selectItem']) {
            this.ngZone.runOutsideAngular(() => {
                this.timer = setTimeout(() => {
                    this.multiSelectCmp['selectItem'](this.selectedFieldIds[0]);
                });
            });
        }
    }

    ngOnDestroy(): void {

    }
    /**
     * 过滤筛选条支持的字段
     * @param treeData 树数据
     */
    filterAllowedType(treeData: TreeNode[]) {
        treeData.forEach(treeNode => {

            if (treeNode.data.$type === FormSchemaEntityField$Type.SimpleField) {
                this.treeNodeIds.push(treeNode.data.id);
                // this.plainTreeNodes.push(treeNode);
            }
            if (treeNode.children && treeNode.children.length > 0) {
                this.filterAllowedType(treeNode.children);
            }
        });
    }
    private filterSchemFields() {
        const removedFields = [];
        this.selectedFieldIds.forEach(id => {
            if (!this.treeNodeIds.includes(id)) {
                // schema中已移除的字段
                const field = this.fieldConfigs.find(f => f.id === id);
                if (field) {
                    removedFields.push(field.title);
                }
                this.fieldConfigs = this.fieldConfigs.filter(f => f.id !== id);
                this.selectedFieldIds = this.selectedFieldIds.filter(fid => fid !== id);
            }
        });
        if (removedFields.length > 0) {
            this.ngZone.runOutsideAngular(() => {
                setTimeout(() => {
                    this.msgService.warning('已选择字段【' + removedFields.toString() + '】已移除、变更或暂不支持添加，点击确定后将自动删除字段');
                });
            });
        }
    }

    /**
     * 改变选中字段事件
     * @param e 选中的行数据
     */
    changeSelectField(e: any[]) {
        if (!e) {
            return;
        }
        const fieldConfigs = [];
        if (e.length === 0) {
            this.propertyConfig = [];
            this.fieldConfigs = [];
            return;
        }
        e.forEach(data => {
            const co = this.fieldConfigs.find(c => c.id === data.id);
            if (co) {
                fieldConfigs.push(co);
            } else {
                const newConfig = this.calendarFieldServ.getCalendarFieldBySchema(data);
                fieldConfigs.push(newConfig);

            }
        });
        this.fieldConfigs = fieldConfigs;


        if (this.selectedSchemaField && !fieldConfigs.find(f => f.id === this.selectedSchemaField.id)) {
            this.propertyConfig = [];
        }
    }

    /**
     * 切换右侧行
     * @param e 行数据
     */
    changeRightSelect(e) {
        if (!e.selected || !e.data) {
            return;
        }
        this.triggerShowPropertyPanel(e.data);
    }

    triggerShowPropertyPanel(rowData: any) {
        this.selectedSchemaField = rowData;

        this.propertyData = this.fieldConfigs.find(f => f.id === rowData.id);
        this.propertyConfig = this.calendarFieldServ.getPropertyConfig(this.propertyData, this.selectedSchemaField);

    }

    clickCancel() {

        this.closeModal.emit();
    }

    clickConfirm() {
        if (this.fieldConfigs.length === 0) {
            this.notifyService.warning('请选择字段');
            return;
        }

        this.submitModal.emit({ value: this.fieldConfigs });
    }
}
